package com.thghh.executor;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 包名称：com.thghh.executor
 * 类名称：TaskAdapter
 * 类描述：一组在某个时间同时完成的线程执行的任务
 * 创建人：@author pengzhikang
 * 创建时间：2021/9/3 9:19
 */
@Data
public class TaskAdapter<V> implements Callable<V> {

    private Logger logger;
    /** 任务组id */
    private int groupId;
    /** 任务id */
    private int taskId;
    /** 线程同步计数器 */
    private CountDownLatch countDownLatch;
    /** 任务执行者 */
    private Task<V> task;

    public TaskAdapter(int groupId, int taskId, CountDownLatch countDownLatch, Task<V> task) {
        this.groupId = groupId;
        this.taskId = taskId;
        this.countDownLatch = countDownLatch;
        this.task = task;
        this.logger = LoggerFactory.getLogger(task.getClass());
    }

    @Override
    public final V call() throws Exception {
        long startTimeMill = System.currentTimeMillis();
        V value = null;
        try {
            value = task.task();
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
            // ignore/reset
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            long timeMill = System.currentTimeMillis() - startTimeMill;
            logger.info("任务组{}任务{}运行时间{}ms", groupId, taskId, timeMill);
            countDownLatch.countDown();
        }
        return value;
    }
}
